<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;

class PaymentsController extends Controller
{
    public function pay(Request $request)
    {
        $this->validate($request, [
            'pay_type' => 'required|in:alipay,wechat_pay',
            'uid' => 'required',
            'out_trade_no' => 'required'
        ], [
            'pay_type.required' => '支付方式不能为空',
            'pay_type.in' => '只支持微信支付和支付宝支付',
            'uid.required' => '用户 ID 不能为空',
            'out_trade_no.required' => '订单号不能为空',
        ]);

        // 查询待款订单
        $unionOrder = UnionOrder::getOneOrder([
            'union_order_id' => $request->out_trade_no,
            'buyer_id' => $request->uid,
            'order_state_id' => 1
        ]);
        if (!$unionOrder) {
            return $this->failed("不存在此待付款订单");
        }

        // 付款金额，测试环境下为 0.01 元
        $total_amount = app()->environment('production') ? $unionOrder->trade_payment_amount : 0.01;

        // 支付宝支付
        $payinfo = [
            'out_trade_no' => $request->out_trade_no,
            'total_amount' => $total_amount,
            'subject' => $unionOrder->trade_title
        ];

        // 微信支付
        if ($request->pay_type == 'wechat_pay') {
            $payinfo = [
                'out_trade_no' => $request->out_trade_no,
                'total_fee' => $total_amount * 100,
                'body' => $unionOrder->trade_title
            ];
        }

        return $this->success(app($request->pay_type)->app($payinfo)->getContent());
    }
}
